package com.diaohw.platform.common.util;

import java.util.concurrent.*;

public class ThreadUtil extends cn.hutool.core.thread.ThreadUtil {

    /**
     * 创建 CountDownLatch
     */
    public static CountDownLatch createCountDownLatch() {
        return createCountDownLatch(1);
    }

    /**
     * 创建 CountDownLatch
     */
    public static CountDownLatch createCountDownLatch(int count) {
        return new CountDownLatch(count);
    }

    /**
     * 等待 CountDownLatch await
     */
    public static void await(CountDownLatch latch) {
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    /**
     * 等待 CountDownLatch await
     */
    public static void await(CountDownLatch latch, long timeout, TimeUnit unit) {
        try {
            latch.await(timeout, unit);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    /**
     * 等待 CountDownLatch await
     */
    public static void awaitThrow(CountDownLatch latch) {
        try {
            latch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 等待 CountDownLatch await
     */
    public static void awaitThrow(CountDownLatch latch, long timeout, TimeUnit unit) {
        try {
            latch.await(timeout, unit);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 异步线程取值
     */
    public static <T> T getFuture(Future<T> future) {
        try {
            return future.get();
        } catch (ExecutionException | InterruptedException e) {
            return null;
        }
    }

    /**
     * 异步线程取值
     *
     * @param timeout 超时时间
     * @param unit    单位
     */
    public static <T> T getFuture(Future<T> future, long timeout, TimeUnit unit) {
        try {
            return future.get(timeout, unit);
        } catch (ExecutionException | InterruptedException | TimeoutException e) {
            return null;
        }
    }

    /**
     * 异步线程取值
     */

    public static <T> T getFutureThrow(Future<T> future) {
        try {
            return future.get();
        } catch (ExecutionException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 异步线程取值
     *
     * @param timeout 超时时间
     * @param unit    单位
     */
    public static <T> T getFutureThrow(Future<T> future, long timeout, TimeUnit unit) throws RuntimeException {
        try {
            return future.get(timeout, unit);
        } catch (ExecutionException | InterruptedException | TimeoutException e) {
            throw new RuntimeException(e);
        }
    }
}
